package cn.highedu.coolsharkhub.filter;

import cn.highedu.coolsharkhub.entity.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 访问过滤器
 * 用于拦截没有登录的用户访问后台资源
 * 如果没有登录 跳转到登录页面
 * 如果已经登录 就放行
 */
@WebFilter(filterName = "accessFilter", urlPatterns = {"/admin.html", "/products/*",
        "/categories/*", "/banners/*"})
public class SecurityFilter implements Filter {
    Logger logger = LoggerFactory.getLogger(SecurityFilter.class);
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("登录访问过滤器");
        // 类型转换
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        // 获取session
        HttpSession session = req.getSession();
        // 获取登录对象
        UserVO userVO = (UserVO) session.getAttribute("user");
        // 判断登录对象是否存在
        if (userVO != null) {
            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
            logger.info("放行");
        }
        else {
            // 访问登录页面
            resp.sendRedirect("/login.html"); // 重定向
            logger.info("重定向到登录页面");
        }
    }
}
